package mdm.com.web.controller;

import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.com.web.common.AjaxResponse;
import mdm.com.web.common.BaseController;
import mdm.com.web.common.Constant;
import mdm.com.web.entity.User;
import mdm.com.web.service.UserService;
import mdm.com.web.session.TokenUtil;

@Controller
@RequestMapping("user")
@Api(description = Constant.MODULE_USER)
public class UserController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "新增用户", notes = "请求参数:<br>" + "cUsername 用户名<br>" + "cPassword 用户密码<br>" + "cNickname 姓名<br>"
            + "cSex 性别<br>" + "cAge 年龄<br>" + "cAvatar 头像<br>" + "cDepartmentId 部门id<br>" + "cRoleId 职位id<br>"
            + "cPermissionIds 权限id")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResponse add(@RequestBody User user, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(user.getcUsername()) || StringUtils.isEmpty(user.getcPassword())) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, "",
                        null);
            }
            if (userService.selectByUsername(user.getcUsername()) != null) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, "用戶名已存在", null);
            }
            Integer userId = TokenUtil.getUserId(TokenUtil.getToken(request));
            user.setcOperatorId(userId);
//            if(user.getcRoleId()==1) {
//                user.setUser_type(null);
//            }
            userService.add(user);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "删除用户", notes = "请求参数:<br>" + "cUserId 用户id")
    @ResponseBody
    @RequestMapping(value = "/remove/{cUserId}", method = RequestMethod.DELETE)
    public AjaxResponse remove(@PathVariable Integer cUserId) {
        try {
            LOGGER.info("------------param:{}", cUserId);
            if (cUserId == null) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, "User ID does not exist", null);
            }
            userService.remove(cUserId);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "修改用户信息", notes = "请求参数:<br>" + "cUserId 用户id<br>" + "cUsername 用户名<br>" + "cNickname 姓名<br>"
            + "cSex 性别<br>" + "cAge 年龄<br>" + "cAvatar 头像<br>" + "cDepartmentId 部门id<br>" + "cRoleId 职位id<br>"
            + "cPermissionIds 权限id")
    @ResponseBody
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    public AjaxResponse modify(@RequestBody User user) {
        try {
            LOGGER.info("------------param:{}", user);
            User u = userService.selectByUsername(user.getcUsername());
            if (u != null && !Objects.equals(user.getcUserId(), u.getcUserId())) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, "", null);
            }
//            if(user.getcRoleId()==1) {
//                user.setUser_type(null);
//            }
            userService.modify(user);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "修改个人信息", notes = "请求参数:<br>" + "cUsername 用户名<br>" + "cNickname 姓名<br>" + "cSex 性别<br>"
            + "cAge 年龄<br>" + "cAvatar 头像")
    @ResponseBody
    @RequestMapping(value = "/modifySelfInfo", method = RequestMethod.PUT)
    public AjaxResponse modifySelfInfo(HttpServletRequest request, @RequestBody User user) {
        try {
            LOGGER.info("------------param:{}", user);
            User u = userService.selectByUsername(user.getcUsername());
            if (u != null && !Objects.equals(user.getcUserId(), u.getcUserId())) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, "", null);
            }
            userService.modify(user);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "用户查询", notes = "请求参数:<br>" + "pageIndex 页码<br>" + "limit 每页显示条数<br>" + "可选查询条件:<br>"
            + "cUsername 用户名<br>" + "cNickname 用户昵称<br>" + "cSex 性别<br>" + "cAgeStart 起始年龄<br>" + "cAgeEnd 结束年龄<br>"
            + "cDepartmentId 部门id<br>" + "cRoleId 职位id<br>" + "cPermissionIds 权限id" + "startDate 开始时间<br>"
            + "endDate 结束时间")
    @ResponseBody
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public AjaxResponse page(@RequestBody User user, @RequestParam Integer pageIndex, @RequestParam Integer limit) {
        try {
            LOGGER.info("------------user page select:{}---{}---{}", user, pageIndex, limit);
            PageHelper.startPage(pageIndex, limit);
            List<User> users = userService.selectAll();
            PageInfo<User> result = new PageInfo<>(users);
            user.setOffset((pageIndex - 1) * limit);
            user.setLimit(limit);
            List<User> list = userService.selectByCondition(user);
            result.setList(list);
//            System.out.println("size:"+result.getList().size());
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "修改用户密码", notes = "请求参数:<br>" + "cUserId 用户id<br>" + "cPassword 新密码")
    @ResponseBody
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.PUT)
    public AjaxResponse modifyPassword(@RequestBody User user) {
        try {
            LOGGER.info("------------param:{}", user);
            
            userService.modifyPassword(user);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }


}
